<script setup>
import { Plus } from 'lucide-vue-next'
import { fileUploadAPI } from '@/api'
import { ElMessage } from 'element-plus'
import errorLogger from '@/utils/errorLogger'
import { ref } from 'vue'

defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])

// 上传图片
const handleUpload = async ({ file }) => {
  try {
    const result = await fileUploadAPI(file)
    emit('update:modelValue', result.data.url)
    ElMessage.success('封面上传成功')
  } catch (error) {
    errorLogger(error)
  }
}

const handleRemove = () => {
  emit('update:modelValue', '')
}

// 图片预览
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
</script>

<template>
  <el-upload
    class="uploader"
    list-type="picture-card"
    :limit="1"
    :auto-upload="true"
    :http-request="handleUpload"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove">
    <template #default>
      <el-icon><Plus /></el-icon>
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img class="preview-img" :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<style lang="scss" scoped>
.uploader {
  margin-bottom: 8px;
}

.preview-img {
  width: 100%;
}
</style>
